package cn.org.qary.controller.qhn.front;

import cn.org.qary.entity.User;
import cn.org.qary.service.trait.qhn.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 *前端用户登录，注册的控制层
 */
@Controller
@RequestMapping("users")
public class UsersController {
    @Autowired
    UsersService usersService;

    /**
     * 用户登录
     * @param user
     * @param session
     * @param ra
     * @return
     */
    @RequestMapping("login")
    public String login(User user, HttpSession session, RedirectAttributes ra){

        User u = usersService.login(user.getUsername(),user.getPassword());
        if (u != null){
            session.setAttribute("user",u);
            return "redirect:/type/init";
        }else {
            ra.addFlashAttribute("msg","用户名或密码错误");
            return "redirect:/users/tologin";
        }
    }
    @RequestMapping("tologin")
    public String tologin(){
        return "login";
    }

    /**
     * 用户注册
     * @param u
     * @param session
     * @param ra
     * @return
     */
    @RequestMapping("register")
    public String register(User u,HttpSession session, RedirectAttributes ra){

        boolean b = usersService.selectByName(u.getUsername());
        if (u == null){
            return "redirect:/register.jsp";
        }else if (!b){
            ra.addFlashAttribute("msg","用户名已经被注册");
            return "redirect:/register.jsp";
        }else {
            usersService.register(u);
            session.setAttribute("users",u);
            return "redirect:tologin";
        }
    }
}
